/**
 * @swagger
 * /api/room/comparison-analysis:
 *   get:
 *     tags:
 *       - 房屋管理
 *     summary: 获取房屋对比分析数据
 *     description: 对比不同房屋的使用情况、面积和效率
 *     responses:
 *       200:
 *         description: 成功获取对比分析数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
 *                   type: integer
 *                   example: 200
 *                   description: 响应状态码
 *                 message:
 *                   type: string
 *                   example: "对比分析获取成功"
 *                   description: 响应消息
 *                 data:
 *                   type: object
 *                   properties:
 *                     areaComparison:
 *                       type: object
 *                       properties:
 *                         buildingVsUsage:
 *                           type: object
 *                           properties:
 *                             buildingArea:
 *                               type: number
 *                               description: 建筑面积
 *                             usageArea:
 *                               type: number
 *                               description: 使用面积
 *                             difference:
 *                               type: string
 *                               description: 面积差值
 *                             ratio:
 *                               type: string
 *                               description: 使用面积占建筑面积比例
 *                             
 *                         constructionVsBuilding:
 *                           type: object
 *                           properties:
 *                             constructionArea:
 *                               type: number
 *                               description: 总建筑面积
 *                             buildingArea:
 *                               type: number
 *                               description: 学校办学总建筑面积
 *                             difference:
 *                               type: string
 *                               description: 面积差值
 *                             ratio:
 *                               type: string
 *                               description: 建筑面积占总建筑面积比例
 *                             
 *                     extremeValues:
 *                       type: object
 *                       properties:
 *                         maximum:
 *                           type: object
 *                           properties:
 *                             name:
 *                               type: string
 *                               description: 指标名称
 *                             value:
 *                               type: number
 *                               description: 指标值
 *                             unit:
 *                               type: string
 *                               description: 单位
 *                         minimum:
 *                           type: object
 *                           properties:
 *                             name:
 *                               type: string
 *                               description: 指标名称
 *                             value:
 *                               type: number
 *                               description: 指标值
 *                             unit:
 *                               type: string
 *                               description: 单位
 *                         
 *                     areaRelationship:
 *                       type: object
 *                       properties:
 *                         usageEfficiency:
 *                           type: string
 *                           description: 使用效率
 *                         spaceUtilization:
 *                           type: string
 *                           description: 空间利用率
 *                         buildingDensity:
 *                           type: string
 *                           description: 建筑密度
 *                         relationships:
 *                           type: array
 *                           items:
 *                             type: object
 *                             properties:
 *                               relationship:
 *                                 type: string
 *                                 description: 关系类型
 *                               efficiency:
 *                                 type: string
 *                               description: 效率值
 *                     allIndicators:
                       type: object
                       description: 所有指标的详细数据
 *       500:
 *         description: 服务器内部错误
 */
const { query } = require('../../../lib/db')
const { success, error, handleResponse } = require('../../../lib/response')
const { withCors } = require('../../../lib/cors')

/**
 * 处理房屋对比分析请求
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
async function handler(req, res) {

  try {
    const sql = `
      SELECT 
        SUM(ZFJJS) as totalRooms,
        SUM(GYFJS) as publicRooms,
        SUM(LDS) as buildingCount,
        SUM(XGBGYFTDSM) as officeLandAcres,
        SUM(TJTDMS) as totalLandAcres,
        SUM(XXBXZJZMJ) as totalBuildingArea,
        SUM(XXBXZSYYMJ) as totalUsageArea,
        SUM(ZJZMJ) as totalConstructionArea
      FROM wd_zcgk_bxzyhz
    `

    const result = await query(sql)
    
    if (!result || result.length === 0) {
      return handleResponse(res, error('暂无房产数据', 404))
    }

    const data = result[0]
    const totalRooms = parseInt(data.totalRooms) || 0
    const publicRooms = parseInt(data.publicRooms) || 0
    const buildingCount = parseInt(data.buildingCount) || 0
    const officeLandAcres = parseFloat(data.officeLandAcres) || 0
    const totalLandAcres = parseFloat(data.totalLandAcres) || 0
    const totalBuildingArea = parseFloat(data.totalBuildingArea) || 0
    const totalUsageArea = parseFloat(data.totalUsageArea) || 0
    const totalConstructionArea = parseFloat(data.totalConstructionArea) || 0

    // 构建所有指标数据
    const indicators = {
      totalRooms: { name: '总房间数', value: totalRooms, unit: '间' },
      publicRooms: { name: '公用房间数', value: publicRooms, unit: '间' },
      buildingCount: { name: '楼栋数', value: buildingCount, unit: '栋' },
      officeLandAcres: { name: '办公用房土地', value: officeLandAcres, unit: '亩' },
      totalLandAcres: { name: '统计土地面积', value: totalLandAcres, unit: '亩' },
      totalBuildingArea: { name: '学校办学总建筑面积', value: totalBuildingArea, unit: '㎡' },
      totalUsageArea: { name: '学校办学总使用面积', value: totalUsageArea, unit: '㎡' },
      totalConstructionArea: { name: '总建筑面积', value: totalConstructionArea, unit: '㎡' }
    }

    // 找出最大最小值
    const values = Object.values(indicators).map(item => ({ name: item.name, value: item.value, unit: item.unit }))
    const maxIndicator = values.reduce((max, current) => current.value > max.value ? current : max)
    const minIndicator = values.reduce((min, current) => current.value < min.value && current.value > 0 ? current : min)

    // 对比分析
    const comparisonAnalysis = {
      // 建筑面积和使用面积对比
      areaComparison: {
        buildingVsUsage: {
          buildingArea: totalBuildingArea,
          usageArea: totalUsageArea,
          difference: (totalBuildingArea - totalUsageArea).toFixed(2),
          ratio: totalBuildingArea > 0 ? ((totalUsageArea / totalBuildingArea) * 100).toFixed(2) : 0,

        },
        constructionVsBuilding: {
          constructionArea: totalConstructionArea,
          buildingArea: totalBuildingArea,
          difference: (totalConstructionArea - totalBuildingArea).toFixed(2),
          ratio: totalConstructionArea > 0 ? ((totalBuildingArea / totalConstructionArea) * 100).toFixed(2) : 0,

        }
      },

      // 各指标最值分析
      extremeValues: {
        maximum: maxIndicator,
        minimum: minIndicator,

      },

      // 面积指标关系分析
      areaRelationship: {
        usageEfficiency: totalBuildingArea > 0 ? ((totalUsageArea / totalBuildingArea) * 100).toFixed(2) : 0,
        spaceUtilization: totalConstructionArea > 0 ? ((totalUsageArea / totalConstructionArea) * 100).toFixed(2) : 0,
        buildingDensity: totalLandAcres > 0 ? (totalBuildingArea / (totalLandAcres * 666.67)).toFixed(4) : 0,
        relationships: [
          {
            relationship: '使用面积 vs 建筑面积',
            efficiency: totalBuildingArea > 0 ? ((totalUsageArea / totalBuildingArea) * 100).toFixed(2) + '%' : '0%'
          },
          {
            relationship: '房间数 vs 楼栋数',
            efficiency: buildingCount > 0 ? (totalRooms / buildingCount).toFixed(2) + '间/栋' : '0间/栋'
          }
        ]
      },

      // 原始数据
      allIndicators: indicators
    }

    return handleResponse(res, success(comparisonAnalysis, '对比分析获取成功'))

  } catch (err) {
    console.error('对比分析接口错误:', err)
    return handleResponse(res, error('服务器内部错误', 500))
  }
}

export default withCors(handler, ['GET'])